package com.zhugang.week13.linkedlist;

/**
 * @program algorithms
 * @description: oddEvenList
 * @author: chanzhugang
 * @create: 2022/10/27 00:24
 */
public class OddEvenList {


    /**
     * 328 奇偶链表
     * https://leetcode.cn/problems/odd-even-linked-list/
     *
     * @param head
     * @return
     */
    public ListNode oddEvenList(ListNode head) {
        // 定义奇链表，奇数尾插、偶链表，偶数尾插，
        ListNode oddList = new ListNode();
        ListNode oddTail = oddList;

        ListNode eventList = new ListNode();
        ListNode eventTail = eventList;

        ListNode p = head;
        int count = 1;
        while (p != null) {
            ListNode next = p.next;
            if (count % 2 == 1) {
                // 尾插法
                oddTail.next = p;
                oddTail = p;
                p.next = null;
            }
            if (count % 2 == 0) {
                eventTail.next = p;
                eventTail = p;
                p.next = null;
            }
            count++;
            p = next;
        }
        // 接上偶链表
        oddTail.next = eventList.next;
        return oddList.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}